package pprz.light;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

public class LightContainer extends Container
 {

	static final long serialVersionUID=1;
	protected Paint backgroundPaint;
	protected LightBorder border;
	protected boolean paintBorder;
	

	protected BufferedImage buff;
	
	public LightContainer()
	{
		backgroundPaint=new Color(0f,0f,0f,0f);
		border=new LightBorder(new Rectangle(0,0,1,1),2);
		border.setForeground(Color.white);
		setLayout(null);
		paintBorder=false;
		buff=new BufferedImage(
				1,
				1,
				BufferedImage.TYPE_4BYTE_ABGR
				);

	}
	
	public Paint getBackgroundPaint() {
		return backgroundPaint;
	}
	public void setBackgroundPaint(Paint background) {
		this.backgroundPaint = background;
	}

	public boolean isPaintBorder() {
		return paintBorder;
	}

	public void setPaintBorder(boolean paintBorder) {
		this.paintBorder = paintBorder;
		if (paintBorder)
			this.add(border);
		else remove(border);
	}

	public void setBorderColor(Color c)
	{
		border.setForeground(c);
	}
	
	public LightBorder getBorder() {
		return border;
	}

	public void setBorder(LightBorder border) {
		this.border = border;
	}

	@Override
	public void paint(Graphics g) {
		if (paintBorder) g.setClip(border.shape);
		g.drawImage(buff,0,0,null);
		super.paint(g);
	}

	protected void draw(Graphics g)
	{
		Graphics2D g2=(Graphics2D)g;
		g2.setComposite(AlphaComposite.Src);
		g2.setPaint(backgroundPaint);
		g2.fill(border.getShape());
	}
	
	
	@Override
	public void setBounds(int x, int y, int width, int height) {
		super.setBounds(x, y, width, height);
		if (width<1 || height<1) return;
		border.setBounds(x, y, width, height);
		
		if (	   buff==null 
				|| buff.getWidth()!=width 
				|| buff.getHeight()!=height
			) {
			buff=new BufferedImage(
					width,
					height,
					BufferedImage.TYPE_4BYTE_ABGR
					);
		}		
	}

	@Override
	public void doLayout() {
		border.setBounds(0, 0, getWidth(), getHeight());
		super.doLayout();
	}

	@Override
	public void validate() {
		super.validate();
//		System.out.println("validate-LightContainer");
		this.draw(buff.getGraphics());
		
	}

	
	
	
	
}
